import { css } from '@emotion/react'
import { Tag, Button, Select, message, Input } from 'antd'
import { EditModal, Loading, Empty } from '@/desktop/components'
import  defaultAvatar  from '@/desktop/assets/avatar.jpg'
import { useStreams } from '@/lib/utils'
import services from '@/services'
import { type MobileSearchResult } from '@/services/contact-types/externals'
import { makeContactId } from '@/services/contacts'

export function MobileApply({
  open,
  initialMobile,
  onClose,
}: {
  open: boolean
  initialMobile?: string
  onClose: (joined: boolean) => void
}) {
  return <EditModal title="手机号加人" width="650px" open={open} onCancel={() => onClose(false)}>
    {open ? <Content initialMobile={initialMobile ?? ''} onClose={onClose} /> : null}
  </EditModal>
}

function Content({
  initialMobile,
  onClose,
}: {
  initialMobile: string
  onClose: (joined: boolean) => void
}) {
  const [qywxs] = useStreams(services.qywxs.alives)
  const [externals] = useStreams(services.externals.list)

  const [wxid, setWxid] = useState<null | string>(null)
  const [mobile, setMobile] = useState(initialMobile)
  const [contact, setContact] = useState<undefined | null | MobileSearchResult>(undefined) // undefined: 没搜索过 null: 没搜到
  const [searching, setSearching] = useState(false)
  function search() {
    if (wxid !== null && mobile) {
      setSearching(true)
      void services.externals.search.byMobile(wxid, mobile).then(res => {
        setSearching(false)
        if (res.success) {
          setContact(res.data)
        } else {
          void message.warning(res.error)
          setContact(null)
        }
      })
    }
  }

  const contactUserId = contact?.uin ?? ''
  // 有值说明 contact 是否已经是此企微的联系人（但有可能是“已删除好友”的状态）
  const external = externals.get(makeContactId(wxid ?? '', contactUserId))
  // 其他已拥有此联系人的企微
  const otherOwnedQywxs = useMemo(() => {
    return [...qywxs.values()].filter(
      qywx => qywx.wxid !== wxid && externals.has(makeContactId(qywx.wxid, contactUserId)),
    )
  }, [qywxs, externals, wxid, contactUserId])

  function goChat() {
    void services.contacts.current.mark(makeContactId(wxid ?? '', contactUserId))
    onClose(true)
  }

  const [verify, setVerify] = useState('') // 加好友欢迎语
  const [sending, setSending] = useState(false)
  async function send() {
    setSending(true)
    const res = await services.externals.search.applyByMobile({
      wxid: wxid ?? '',
      userId: contactUserId,
      wxTicket: contact?.wx_ticket ?? '',
      openid: contact?.openid ?? '',
      verify,
    })
    if (res.success) {
      void message.success('请求发送成功')
    } else {
      void message.error('请求发送失败：' + res.error)
    }
    setSending(false)
  }

  let result: React.ReactNode = null
  if (contact !== undefined) {
    if (searching) {
      result = <Loading />
    } else if (!contact) {
      result = <Empty description="没有匹配的联系人" />
    } else {
      result = <>
        <div css={[styles.row, styles.info]}>
          <img src={contact.iconurl || defaultAvatar} />

          <div className="detail">
            <div className="name-wrap">
              <span className="name">{contact.name}</span>
              {external && external.deleted !== null ? <Tag>删</Tag> : null}
            </div>
            {!external && otherOwnedQywxs.length ? (
              <div css={styles.otherQywxs}>
                <span>所属企微：</span>
                {otherOwnedQywxs.map(v => <a key={v.wxid}>{v.friendlyFullName}</a>)}
              </div>
            ) : null}
          </div>

          {external ? (
            external.deleted === null ? (
              <Button type="primary" onClick={goChat}>
                进入聊天
              </Button>
            ) : (
              <Button onClick={goChat}>查看联系人</Button>
            )
          ) : null}
        </div>
        {!external || external.deleted !== null ? (
          <div css={styles.apply}>
            <Input.TextArea
              placeholder="输入验证信息"
              value={verify}
              onChange={e => setVerify(e.target.value)}
              rows={4}
            />
            <Button type="primary" loading={sending} onClick={send}>
              添加好友
            </Button>
          </div>
        ) : null}
      </>
    }
  }

  return <main>
    <div css={styles.row}>
      <label>加人企微：</label>
      <div>
        <Select
          css={styles.select}
          options={[...qywxs.values()].map(qywx => ({
            label: qywx.friendlyFullName,
            value: qywx.wxid,
          }))}
          value={wxid}
          onChange={wxid => setWxid(wxid)}
          status={wxid !== null ? '' : 'error'}
        />
        {wxid === null ? <div css={styles.tips}>请选择要加人的企业微信</div> : null}
      </div>
    </div>
    <div css={styles.row}>
      <label>手机号：</label>
      <Input
        css={styles.input}
        placeholder="输入手机号"
        value={mobile}
        onChange={e => setMobile(e.target.value.toString())}
      />
    </div>
    <div css={styles.row}>
      <label></label>
      <Button type="primary" disabled={wxid === null || !mobile} onClick={search}>
        搜索
      </Button>
    </div>

    <div css={styles.result}>{result}</div>
  </main>
}

const styles = {
  row: css`
    display: flex;
    align-items: baseline;
    margin-bottom: 20px;
    label {
      width: 6em;
      flex-shrink: 0;
      text-align: right;
    }
  `,
  select: css`
    width: 20em;
  `,
  tips: css`
    font-size: 13px;
    margin-top: 4px;
    color: #f5222d;
  `,
  input: css`
    width: 20em;
  `,
  result: css`
    min-height: 300px;
  `,

  info: css`
    border-top: 1px solid #f0f0f0;
    border-bottom: 1px solid #f0f0f0;
    padding: 12px;
    align-items: center;
    img {
      border-radius: 8px;
      height: 45px;
      width: 45px;
      margin-right: 12px;
    }
    .detail {
      flex: 1;
      margin-right: 0.5em;
    }
    .name {
      color: #555;
      font-weight: bold;
      margin-right: 0.5em;
      word-break: break-all;
      word-wrap: break-word;
    }
  `,

  otherQywxs: css`
    margin-top: 4px;
    font-size: 12px;
    a {
      cursor: default;
    }
  `,

  apply: css`
    text-align: right;
    button {
      margin-top: 12px;
    }
  `,
}
